package com.jinliang.thinkinredis.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class PowerReqAspect {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 环绕通知：灵活自由的在目标方法中切入代码
     */
    @Around("@annotation(powerReq)")
    public Object around(ProceedingJoinPoint joinPoint, PowerReq powerReq) throws Throwable {
        // 获取待锁定的参数index
        int lockIndexParam = powerReq.lockIndexParam();
        // 获取方法传入参数
        Object[] params = joinPoint.getArgs();
        String i = params[lockIndexParam - 1].toString();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object o = valueOperations.get(String.valueOf(i));
        if (Objects.isNull(o)) {
            valueOperations.set(String.valueOf(i), String.valueOf(i), powerReq.leaseTime(), TimeUnit.SECONDS);
            return joinPoint.proceed();
        }
        throw new Exception("数据已提交请等待");


    }
}
